package ldz.Manager;

import ldz.lian.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ManagerDaoImpl implements ManagerDao {

    @Override
    public int insertManager(String mno, String mname, String mpassword) {
        int result = 0;
        String sql = "INSERT INTO manager (Mno, Mname, Mpassword) VALUES (?,?,?)";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setString(1, mno);
            preparedStatement.setString(2, mname);
            preparedStatement.setString(3, mpassword);
            result = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public int deleteManager(String mno) {
        int result = 0;
        String sql = "DELETE FROM manager WHERE Mno =?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setString(1, mno);
            result = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public List<Manager> getAllManagers() {
        List<Manager> managerList = new ArrayList<>();
        String sql = "SELECT Mno, Mname, Mpassword FROM manager";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql);
             ResultSet resultSet = preparedStatement.executeQuery()) {
            while (resultSet.next()) {
                Manager manager = new Manager();
                manager.setMno(resultSet.getString("Mno"));
                manager.setMname(resultSet.getString("Mname"));
                manager.setMpassword(resultSet.getString("Mpassword"));
                managerList.add(manager);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return managerList;
    }

    @Override
    public int updateManager(String mno, String newMpassword) {
        int result = 0;
        String sql = "UPDATE manager SET Mpassword =? WHERE Mno =?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setString(1, newMpassword);
            preparedStatement.setString(2, mno);
            result = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }
}